//
//  MHInComeViewModel.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/7/24.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHInComeViewModel.h"
#import "MHInComeItemViewModel.h"
#import "MHPurseDetail.h"

@interface MHInComeViewModel()
@property (nonatomic, readwrite, copy) NSArray *incomes;
@end

@implementation MHInComeViewModel
-(void)initialize
{
    [super initialize];
    self.shouldPullUpToLoadMore = YES;
    /// 没有数据时，隐藏底部刷新控件
    self.shouldEndRefreshingWithNoMoreData = NO;
    @weakify(self);
    RAC(self, incomes) = self.requestRemoteDataCommand.executionSignals.switchToLatest;
    /// 数据源
    RAC(self,dataSource) = [RACObserve(self, incomes) map:^(NSArray * repeaters) {
        @strongify(self)
        return [self dataSourceWithRepeaters:repeaters];
    }];
    
//    self.requstAskCountCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
//        @strongify(self);
//        return  [[self.services.client getMyQuestionCountWithCircleId:self.info.autoId] doNext:^(MHHTTPResponse *response) {
//            self.askCount = [[[response parsedResult] objectForKey:@"countQuestion"] intValue];
//            self.dataSource = [self dataSourceWithRepeaters:self.repeaters];
//        }];
//    }];
}

-(instancetype)initWithServices:(id<MHViewModelServices>)services params:(NSDictionary *)params
{
    if (self = [super initWithServices:services params:params]) {
        self.type = [params[MHViewModelUtilKey] intValue];
    }
    return self;
}


- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page{
    
    NSArray * (^mapRepeaters)(NSArray *) = ^(NSArray *incomes) {
        if (page == 1) {
            /// 下拉刷新
        } else {
            /// 上拉加载
            incomes = @[(self.incomes ?: @[]).rac_sequence, incomes.rac_sequence].rac_sequence.flatten.array;
        }
        return incomes;
    };
    
    return [[self.services.client getUserPurseDetailPagedListWithPageNum:page pageSize:self.perPage type:self.type] map:mapRepeaters];
//    return [[self.services.client getCircleQuestionerListWithCircleId:self.info.autoId] map:mapRepeaters];
}

#pragma mark - 辅助方法
- (NSArray *)dataSourceWithRepeaters:(NSArray *)incomes {
    if (MHObjectIsNil(incomes) || incomes.count == 0) return @[];
    NSMutableArray *viewModels = [[incomes.rac_sequence map:^(MHPurseDetail *purse) {
        MHInComeItemViewModel *viewModel = [[MHInComeItemViewModel alloc] initWithModel:purse];
        viewModel.type = self.type;
        //        viewModel.info = self.info;
        return viewModel;
    }].array mutableCopy];

    return viewModels ?: @[] ;
}

@end
